package com.sure.common.dao.model.base;

import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;

import com.sure.common.cache.clazz.ClazzUtil;
import com.sure.common.cache.clazz.POReflectManager;
import com.sure.common.cache.clazz.VOReflectManager;
import com.sure.common.cache.clazz.model.ClassReflect;
import com.sure.common.exception.SystemException;

/**
 * 查询VO映射通用
 * 
 * @author Sure
 *
 * @param <T>
 */
public class BaseRowMapper<T> implements RowMapper<T> {
	/** 对应类 */
	private Class<T> clazz;
	/** 返回列*/
	private List<String> returnCols;
	
	public BaseRowMapper(Class<T> clazz,List<String> returnCols) {
		this.clazz = clazz;
		this.returnCols = returnCols;
	}
	@SuppressWarnings("rawtypes")
	@Override
	public T mapRow(ResultSet rs, int rowNum) throws SQLException {
		
		try {
			//实例化
			T voInstance = clazz.newInstance();
			//获取其中的PO实例 及其反射信息
			Map<String, ClassReflect> pos = new HashMap<String, ClassReflect>();
			for(Method getMethod : VOReflectManager.get(clazz).getGetMethods()) {
				Object po = getMethod.invoke(voInstance, (Object[])null);
				ClassReflect poReflect = POReflectManager.get(po.getClass());
				poReflect.setInstance(po);
				pos.put(poReflect.getTableName(), poReflect);
			}
			//对每个字段进行赋值
			for(String col: returnCols) {
				ClassReflect reflect = pos.get(getTableName(col));
				//使用set方法赋值
				Object[] args = new Object[]{rs.getObject(ClazzUtil.getAlias(col))};
				reflect.getColumnsMap().get(col)
					.getSetMethod().invoke(reflect.getInstance(),args);
			}
			
			return voInstance;

		}catch (Exception e) {
			return null;
		}
	}
	
	private String getTableName(String colName) throws SystemException {

		String[] res = colName.split(".");
		if (res.length != 2) {
			throw new SystemException("列名信息错误，请使用【tableName.colName】规范填写。");
		}
		return res[0];

	}

}
